package com.apimanage.auth.config;

import com.apimanage.common.utils.JwtTokenUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT认证过滤器,用于拦截请求并验证JWT令牌
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    @Autowired
    private UserDetailsService userDetailsService;

    public JwtAuthenticationFilter() {
        // 构造函数不需要注入JwtTokenUtil，使用静态方法
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 获取Authorization头
        String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);

        // 如果Authorization头为空或不以Bearer开头，则继续过滤器链
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }

        try {
            // 提取JWT令牌
            String jwt = authorizationHeader.substring(7);

            // 先验证Token是否有效
            if (!JwtTokenUtil.validateToken(jwt)) {
                // Token验证失败，返回401错误
                sendUnauthorizedResponse(response, "认证失败：无效的令牌", "JWT令牌验证失败");
                return;
            }

            // 从JWT中获取用户名
            String username = JwtTokenUtil.getUsernameFromToken(jwt);

            // 如果用户名不为空且安全上下文中没有认证信息
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                // 加载用户信息
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                // 创建认证令牌
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                // 设置安全上下文
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (ExpiredJwtException e) {
            // 处理过期异常
            logger.warn("JWT令牌已过期: " + e.getMessage(), e);
            sendUnauthorizedResponse(response, "认证失败：令牌已过期", e.getMessage());
            return;
        } catch (SignatureException e) {
            // 专门处理签名异常
            logger.warn("JWT签名验证失败: " + e.getMessage(), e);
            sendUnauthorizedResponse(response, "认证失败：令牌签名无效", e.getMessage());
            return;
        } catch (Exception e) {
            // 认证失败，清除安全上下文
            SecurityContextHolder.clearContext();
            // 记录详细日志
            logger.warn("JWT认证失败: " + e.getMessage(), e);
            sendUnauthorizedResponse(response, "认证失败：令牌解析错误", e.getMessage());
            return;
        }

        // 验证通过，继续过滤器链
        filterChain.doFilter(request, response);
    }

    private void sendUnauthorizedResponse(HttpServletResponse response, String message, String errorDetail) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        String errorMsg = String.format("{\"code\":\"401\",\"message\":\"%s\",\"errorDetail\":\"%s\"}",
                message, errorDetail);
        response.getWriter().write(errorMsg);
        response.getWriter().flush();
    }
}
